import telegram.api as tg
import telegram.objects as tgo
import asyncdispatch
import terminal
import jsonob
import throw as _
import strutils

proc serve_one(update: tgo.Update) {.async.} =
    if update.message.is_none: return
    let message = update.message.unsafe_get
    if message.text.is_none:
        echo "skipped"
        echo update.to_json.pretty
        return

    let `from` = message.`from`.get
    let  msg_text = message.text.unsafe_get
    let  username = `from`.username.get "@@"
    let  lastname = `from`.last_name.get ""
    let firstname = `from`.first_name
    let msg = "@$# [$# $#]: $#".format(username, firstname, lastname, msg_text)
    echo msg

    async_check tg.send_message(message.chat.id, msg)

proc serve {.async.} =
    var last_update = 0
    while true:
        echo "getting updates..."
        let response = await tg.get_updates(last_update)

        if not response.ok:
            IO_error.throw "failed to get updates ($#): $#", response.error_code.get, response.description.get

        let updates = response.result.get
        for update in updates:
            last_update = update.update_id + 1
            async_check serve_one(update)

proc serve_safe {.async.} =
    var fut = serve()
    await fut

# better error reporting
global_raise_hook = proc (e: ref Exception): bool =
    styled_echo("\e[38;5;238m")        # dimmed grey (256-color terminal required), not available in `terminal` module
    write_stack_trace()
    styled_echo(fg_black, bg_red, " ERROR ", reset_style, " ", e.msg)
    quit(QUIT_FAILURE)

# must reset before quit to avoid console mess
add_quit_proc(reset_attributes)

wait_for serve_safe()

